/**  
 * All rights Reserved, Designed By www.xiaozhanjiaoyu.cn
 * @Title:  MySpeechSynthesizerListener.java   
 * @Package javaapplication.speechsynthesizer   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: knight.lu     
 * @date:   2018年11月21日 下午8:08:07   
 * @version V1.0 
 * @Copyright: 2018 www.xiaozhanjiaoyu.cn Inc. All rights reserved. 
 * 
 */
package com.tts.speechsynthesizer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import com.component.CommonConstant;
import com.component.NotifyObject;
import com.vo.ResultJson;

/**
 * @ClassName: MySpeechSynthesizerListener
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: knight.lu
 * @date: 2018年11月21日 下午8:08:07
 * 
 */
public class CustomSpeechSynthesizerListener extends SpeechSynthesizerListener {

	private static Logger LOG = LoggerFactory.getLogger(CustomSpeechSynthesizerListener.class);

	private File f;

	private FileOutputStream fout;

	// 通知器
	private NotifyObject notifyObject;

	/**
	 * @param notifyObject
	 */
	public CustomSpeechSynthesizerListener(NotifyObject notifyObject) {
		this.notifyObject = notifyObject;
		ResultJson resultJson = notifyObject.getResultJson();
		f = new File(CommonConstant.filePath + File.separator + resultJson.getuId() + ".wav");
		try {
			fout = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resultJson.setPath(f.getAbsolutePath());
	}

	@Override
	public void onComplete(SpeechSynthesizerResponse response) {
		// 事件名称 SynthesisCompleted
		LOG.info("name: " + response.getName() +
		// 状态码 20000000 表示识别成功
				", status: " + response.getStatus() +
				// 语音合成文件路径
				", output file :" + f.getAbsolutePath());
		notifyObject.notifySynthesuzed();
	}

	// 语音合成的语音二进制数据
	@Override
	public void onMessage(ByteBuffer message) {
		try {
			byte[] bytesArray = new byte[message.remaining()];
			message.get(bytesArray, 0, bytesArray.length);
			fout.write(bytesArray);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				fout.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
